import { LOGIN_CODE_KEY, ResCurrentUser } from '@/domain/authority/types/auth/auth';

import { reactive, inject, provide } from 'vue';
// import { getUserInfo } from '@/api/login';
import { getCookie, removeCookie, setCookie } from '@/utils/cookies';
import { getBaseUrl, getQueryVariable } from '@/utils/http';
import { ConsoleLogger } from '@/utils/debug-log';
import { router } from '@/project/crmManage/router';
import { getCurrentUser, getLogoutUrl } from '../api/login';

const console = new ConsoleLogger('登陆');
const useUserInfoSymbol = Symbol('useUserinfo store');

export interface IUserInfoState {
  isLoginStatus: boolean;
  userInfo?: ResCurrentUser; //
  tocken?: string | undefined;
}

export interface IUseUserInfoStoreFn {
  (): IUseUserInfoStore;
  __CurrentStore?: IUseUserInfoStore;
}

export interface IUseUserInfoStore {
  state: IUserInfoState;
  setLoginStatus: (status: boolean) => void;
  gainUserInfo: (code: string) => Promise<boolean>;
  toLoginOut: () => void;
  init: () => void;
}
export const loginStatus = { userInfo: {}, isLoginStatus: false };
/**
 *  * useUserInfoStore 用户hooks.
 * @function
 * @params {IUserInfoState} userState - 用户信息.
 * @returns store extend IUseUserInfoStore
 */
export const useUserInfoProvide: () => IUseUserInfoStore = () => {
  const state = reactive<IUserInfoState>({
    isLoginStatus: true,
    userInfo: undefined,
    tocken: undefined
  });
  const gainUserInfo = async () => {
    const res = await getCurrentUser();
    if (res.data.name) {
      state.userInfo = res.data;
      state.isLoginStatus = true;
      console.log('查询当前用户信息');
      // setCookie('admin_token', token, { domain: '.xiwang.com' });
      return true;
    }
    state.isLoginStatus = false;
    return false;
  };
  const init = async () => {
    await gainUserInfo(); //获取用户信息
  };

  const setLoginStatus = (status: boolean) => {
    state.isLoginStatus = status;
  };

  const toLoginOut = async () => {
    const res = await getLogoutUrl();
    removeCookie(LOGIN_CODE_KEY);
    state.isLoginStatus = false;
    state.userInfo = undefined;
    window.location.reload();
  };

  const store: IUseUserInfoStore = {
    state,
    init,
    setLoginStatus,
    toLoginOut,
    gainUserInfo
  };

  provide(useUserInfoSymbol, { ...store });

  return store;
};

/**
 *  * useUserInfoStore 用户hooks.
 * @function
 * @returns store extend IUseUserInfoStore
 */
export const useUserInfoStore: IUseUserInfoStoreFn = () => {
  const store: IUseUserInfoStore = inject(useUserInfoSymbol) as IUseUserInfoStore;
  return store;
};
